package com.youth.hrsync.config.datasource;

import com.kcis.xian.hrsync.mapper.kunshan.KunShanCheckinoutMapper;
import com.kcis.xian.hrsync.mapper.kunshan.KunShanUserinfoMapper;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "com.kcis.xian.hrsync.mapper.kunshan", sqlSessionFactoryRef = "kunshanSqlSessionFactory")
public class KunShanDataSourceConfig {

    @Bean(name = "kunshanDataSource")
    @ConfigurationProperties(prefix = "spring.datasource-kunshan")
    public DataSource kunshanDataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "kunshanSqlSessionFactory")
    public SqlSessionFactory kunshanSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(kunshanDataSource());
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        String locationPattern = "classpath:/xml/kunshan/*Mapper.xml";
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources(locationPattern));
        return sqlSessionFactoryBean.getObject();
    }

    @Bean(name = "kunshanSqlSessionTemplate")
    public SqlSessionTemplate kunshanSqlSessionTemplate(@Qualifier("kunshanSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory, ExecutorType.BATCH);
    }

    @Bean
    public KunShanUserinfoMapper kunShanUserinfoMapper(@Qualifier("kunshanSqlSessionTemplate") SqlSessionTemplate sqlSessionTemplate) {
        return sqlSessionTemplate.getMapper(KunShanUserinfoMapper.class);
    }

    @Bean
    public KunShanCheckinoutMapper kunShanCheckinoutMapper(@Qualifier("kunshanSqlSessionTemplate") SqlSessionTemplate sqlSessionTemplate) {
        return sqlSessionTemplate.getMapper(KunShanCheckinoutMapper.class);
    }

}
